package jvm.ref;

import java.lang.ref.SoftReference;

/**
 * 软引用
 * @author jiangwz
 * @create 2019/9/17.
 */
public class SoftReferenceDemo {

    /**
     * 内存够用,软引用不会被清除
     */
    public static void softRef_memory_Enough(){

        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference.get());

        o1 = null;
        System.gc();
        System.out.println(o1);
        System.out.println(softReference.get());
    }

    /**
     * 软引用内存不够
     * -Xms5m -Xmx5m -XX:+PrintGCDetails
     */
    public static void softRef_memory_NotEnough(){

        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference.get());

        o1 = null;
        // 让他自动gc
        try {
            byte[] bytes = new byte[30 * 1024 * 1024]; // 30m
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("finally="+o1);
            System.out.println("finally="+softReference.get());
        }

    }

    public static void main(String[] args){

//        softRef_memory_Enough();
        softRef_memory_NotEnough();
    }
}
